<script setup lang="ts">
import { reactive, ref } from 'vue';
import { invoke } from '@tauri-apps/api/tauri';

import type { TabsPaneContext, UploadUserFile } from 'element-plus';
import { ElMessage } from 'element-plus';
import { writeText } from '@tauri-apps/api/clipboard';


// 新增：定义 parseResult 的类型结构
interface ParseResult {
  headers: string[];
  new_headers: string[];
  models: string[];
  sqls: string[];
}

const activeName = ref('first');

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
};

// 英文转变量
const sourceValue = ref('');
const targetValue = ref('');

const handleTranslate = async () => {
  targetValue.value = await invoke('en_to_variable', {
    sourceValue: sourceValue.value,
  });
};

// 文件头部解析
const headerRow = ref<number>(1);

const headerParse = reactive({
  sourceHeader: '',
  parseHeader: '',
  model: '',
  sql: '',
});

const fileList = ref<UploadUserFile[]>([]);
const sumbitFile = async () => {
  const fileContent = await fileList.value[0].raw?.arrayBuffer();
  if (fileContent) {
    const fileData = Array.from(new Uint8Array(fileContent));
    invoke<ParseResult>('handle_file', {
      fileData,
      headerRow: headerRow.value,
    })
      .then((parseResult) => {
        console.log('parseResult', parseResult);
        headerParse.sourceHeader = parseResult.headers.map(item => `"${item}"`).join(',\n');
        headerParse.parseHeader = parseResult.new_headers.map(item => `"${item}"`).join(',\n');
        headerParse.model = parseResult.models.join('\n');
        headerParse.sql = parseResult.sqls.join('\n');
        console.log(parseResult);
      })
      .catch((err) => {
        console.log(err);
        ElMessage.error(err);
      });
  }
};
async function copyToClipboard(text:string) {
  try {
    await writeText(text);
    ElMessage.success('复制成功');
  } catch (err) {
    ElMessage.error('复制失败');
    console.error('复制失败:', err);
  }
}


// 字段对应模态框
const headerFieldMapVisible = ref(false);
let reserve = ref(false);
const headerFieldMap = ref<string>('');

const createHeaderFieldMap = () => {
  console.log(headerParse.sourceHeader);
  const sourceHeaderList = headerParse.sourceHeader.split(",\n");
  const parseHeaderList = headerParse.parseHeader.split(",\n");
  return sourceHeaderList
    .map((item, index) => reserve.value ? `${item}: ${parseHeaderList[index]},` : `${parseHeaderList[index]}: ${item},`)
    .join('\n');
}

const showHeaderFieldMap = () => {
  headerFieldMap.value = createHeaderFieldMap();
  headerFieldMapVisible.value = true;
};

const handleReserve = () => {
  headerFieldMap.value = createHeaderFieldMap();
  reserve.value = !reserve.value;
};

</script>

<template>
  <main class="container">
    <el-tabs
      v-model="activeName"
      tab-position="left"
      class="demo-tabs"
      @tab-click="handleClick"
    >
      <el-tab-pane label="英文转变量" name="first">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              :rows="5"
              v-model="sourceValue"
              type="textarea"
              placeholder="请输入英文"
            />
          </el-col>
          <el-col :span="4" class="!flex flex-col justify-center">
            <el-button type="primary" size="large" @click="handleTranslate"
              >转换</el-button
            >
          </el-col>
          <el-col :span="8">
            <el-input
              :rows="5"
              v-model="targetValue"
              type="textarea"
              placeholder="转换结果"
            />
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="文件头部解析" name="second" class="py-2 px-6">
        <el-row>
          <el-col :span="10" :offset="2">
            <div class="flex" style="gap: 4px">
              <span style="flex-shrink: 0">文件头部位置:</span>
              <el-input-number
                v-model.number="headerRow"
                style="width: 240px"
              />
            </div>
          </el-col>
          <el-col :span="10" :offset="2">
            <el-upload
              v-model:file-list="fileList"
              :show-file-list="false"
              :auto-upload="false"
            >
              <template #trigger>
                <el-button type="primary">选择文件</el-button>
              </template>
              <el-button
                type="success"
                style="margin-left: 20px"
                @click="sumbitFile"
                >解析文件</el-button
              >
            </el-upload>
          </el-col>
        </el-row>
        <template v-if="headerParse.sourceHeader.length > 0">
          <el-divider />
          <el-card>
            <template #header>
              <div class="card-header flex justify-between">
                <span>原始表头</span>
                <el-button type="primary" link @click="copyToClipboard(headerParse.sourceHeader)"> 复制 </el-button>
              </div>
            </template>
            <el-input
              :rows="6"
              v-model="headerParse.sourceHeader"
              type="textarea"
            />
          </el-card>
          <el-divider />
          <el-card>
            <template #header>
              <div class="card-header flex justify-between">
                <span>变量表头</span>
                <el-button type="primary" link @click="copyToClipboard(headerParse.parseHeader)"> 复制 </el-button>
              </div>
            </template>
            <el-input
              :rows="6"
              v-model="headerParse.parseHeader"
              type="textarea"
            />
          </el-card>
          <el-divider />
          <el-card>
            <template #header>
              <div class="card-header flex justify-between">
                <span>Model</span>
                <el-button type="primary" link @click="copyToClipboard(headerParse.model)"> 复制 </el-button>
              </div>
            </template>
            <el-input :rows="6" v-model="headerParse.model" type="textarea" />
          </el-card>
          <el-divider />
          <el-card>
            <template #header>
              <div class="card-header flex justify-between">
                <span>建表语句</span>
                <el-button type="primary" link @click="copyToClipboard(headerParse.sql)"> 复制 </el-button>
              </div>
            </template>
            <el-input :rows="6" v-model="headerParse.sql" type="textarea" />
          </el-card>
          <el-divider />
          <div class="flex justify-end mr-2 mb-2.5" >
            <el-button type="primary" @click="showHeaderFieldMap"> 字段对应 </el-button>
          </div>
        </template>
      </el-tab-pane>
    </el-tabs>
  </main>
  <el-dialog v-model="headerFieldMapVisible" title="字段对应" width="800">
    <div class="flex justify-end mb-4">
        <el-button type="primary" link @click="handleReserve">反转</el-button>
        <el-divider direction="vertical" />
        <el-button type="primary" link @click="copyToClipboard(headerFieldMap)">复制</el-button>
    </div>
     <el-input
      v-model="headerFieldMap"
      :rows="6"
      type="textarea"
    />


    <template #footer>
      <div class="dialog-footer">
        <el-button @click="headerFieldMapVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped></style>
<style>
/* :root {
  font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
  font-size: 16px;
  line-height: 24px;
  font-weight: 400;

  color: #0f0f0f;
  background-color: #f6f6f6;

  font-synthesis: none;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  -webkit-text-size-adjust: 100%;
} */

.container {
  margin: 0;
  padding-top: 10vh;
}
</style>
